package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.CancelTaskDto;
import com.zzyl.nursing.dto.NursingExecuteTaskDto;
import com.zzyl.nursing.dto.NursingTaskPageDto;
import com.zzyl.nursing.dto.TaskDto;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.util.IDCardUtils;
import com.zzyl.nursing.vo.NursingTaskDetailVo;
import com.zzyl.nursing.vo.NursingTaskVo;
import com.zzyl.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.NursingTaskMapper;
import com.zzyl.nursing.domain.NursingTask;
import com.zzyl.nursing.service.INursingTaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 护理任务Service业务层处理
 *
 * @author wrb
 * @date 2025-09-24
 */
@Service
@Slf4j
public class NursingTaskServiceImpl extends ServiceImpl<NursingTaskMapper, NursingTask> implements INursingTaskService {
    @Autowired
    private NursingTaskMapper nursingTaskMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;


    /**
     * 查询护理任务
     *
     * @param id 护理任务主键
     * @return 护理任务
     */
    @Override
    public NursingTaskDetailVo selectNursingTaskById(Long id) {
        NursingTask nursingTask = getById(id);
        //1.拷贝数据
        NursingTaskDetailVo nursingTaskDetailVo = BeanUtil.toBean(nursingTask, NursingTaskDetailVo.class);
        //2.补充缺少的数据
        //2.1护理员姓名列表
        String nursingIdStr = nursingTaskDetailVo.getNursingId();
        //如果不存在护理人员，则不添加
        if (nursingIdStr != null) {
            log.warn("没有查到老人的护理人员，elderId");
            String[] nursingIds = nursingIdStr.split(",");
            //组件对应的护理人员名字
            List<String> nursingName = new ArrayList<>();

            //遍历nursingIds找到对应的名字
            for (String nursingId : nursingIds) {
                String nickName = sysUserMapper.selectUserById(Long.valueOf(nursingId)).getNickName();
                nursingName.add(nickName);
            }
            nursingTaskDetailVo.setNursingName(nursingName);
        }

        //2.2获取护理等级名称,通过checkin表获得
        Long elderId = nursingTaskDetailVo.getElderId();
        CheckIn checkIn = checkInMapper.selectOne(new LambdaQueryWrapper<CheckIn>()
                .eq(CheckIn::getElderId, elderId));
        //如果不存在，则不添加
        if (checkIn != null) {
            log.warn("没有通过checkin表查到老人的护理等级，elderId = {}", elderId);
            nursingTaskDetailVo.setNursingLevelName(checkIn.getNursingLevelName());
        }

        //2.3，获取老人性别,这里通过elder表获得，也可以通过checkin获得
        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>()
                .eq(Elder::getId, elderId));
        //如果不存在，则不添加
        if (checkIn != null) {
            log.warn("没有通过elder表查到老人的护理等级，elderId = {}", elderId);
            //获取老人的身份证
            String idCardNo = elder.getIdCardNo();
            //获取老人的性别
            int genderFromIdCard = IDCardUtils.getGenderFromIdCard(idCardNo);
            nursingTaskDetailVo.setSex(genderFromIdCard == 0 ? "男" : "女");
            //获取老人的年龄
            int ageByIdCard = IDCardUtils.getAgeByIdCard(idCardNo);
            nursingTaskDetailVo.setAge(ageByIdCard);
        }
        //2.4更新人的姓名
        String userId = nursingTask.getUpdateBy();
        if(userId != null){
            nursingTaskDetailVo.setUpdater(sysUserMapper.selectUserById(Long.valueOf(userId)).getNickName());
        }

        return nursingTaskDetailVo;
    }

    /**
     * 查询护理任务列表
     *
     * @param nursingTaskPageDto 护理任务
     * @return 护理任务
     */
    @Override
    public List<NursingTaskVo> selectNursingTaskList(NursingTaskPageDto nursingTaskPageDto) {
        List<NursingTaskVo> nursingTaskVoList = nursingTaskMapper.selectNursingTaskList(nursingTaskPageDto);
        //遍历获取名字
        nursingTaskVoList.forEach(nursingTaskVo -> {
            //获取护理人员的id
            String nursingIdStr = nursingTaskVo.getNursingId();
            //如果不存在护理人员，则退出
            if (nursingIdStr != null) {
                String[] nursingIds = nursingTaskVo.getNursingId().split(",");
                //组件对应的护理人员名字
                List<String> nursingName = new ArrayList<>();
                //遍历nursingIds找到对应的名字
                for (String nursingId : nursingIds) {
                    String nickName = sysUserMapper.selectUserById(Long.valueOf(nursingId)).getNickName();
                    nursingName.add(nickName);
                }
                nursingTaskVo.setNursingName(nursingName);
            }
        });




        return nursingTaskVoList;
    }

    /**
     * 新增护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int insertNursingTask(NursingTask nursingTask) {
        return save(nursingTask) ? 1 : 0;
    }

    /**
     * 修改护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int updateNursingTask(NursingTask nursingTask) {
        return updateById(nursingTask) ? 1 : 0;
    }

    /**
     * 批量删除护理任务
     *
     * @param ids 需要删除的护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除护理任务信息
     *
     * @param id 护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 取消任务 d15 -5
     *
     * @param cancelTaskDto
     */
    @Override
    public int cancelTask(CancelTaskDto cancelTaskDto) {
        //把status = 3 已关闭
        NursingTask nursingTask = new NursingTask();
        //属性补全
        nursingTask.setId(cancelTaskDto.getTaskId());
        nursingTask.setStatus(3);
        nursingTask.setCancelReason(cancelTaskDto.getReason());
        nursingTask.setUpdateTime(new Date());
        //更新人id
        nursingTask.setUpdateBy(SecurityUtils.getUserId().toString());
        return updateNursingTask(nursingTask);
    }

    /**
     * 执行任务 d15 -6
     *
     * @param nursingExecuteTaskDto
     */
    @Override
    public int executeTask(NursingExecuteTaskDto nursingExecuteTaskDto) {
//        复制属性
        NursingTask nursingTask = BeanUtil.toBean(nursingExecuteTaskDto, NursingTask.class);
        //补全与更改
        nursingTask.setId(nursingExecuteTaskDto.getTaskId());
        nursingTask.setStatus(2);
        nursingTask.setUpdateTime(new Date());
        nursingTask.setRealServerTime(nursingExecuteTaskDto.getEstimatedServerTime());

        //更新人id
        nursingTask.setUpdateBy(SecurityUtils.getUserId().toString());
        return updateNursingTask(nursingTask);
    }

    /**
     * 执行任务 d15 -7
     *
     * @param taskDto
     */
    @Override
    public int updateTime(TaskDto taskDto) {
        NursingTask nursingTask = new NursingTask();
        nursingTask.setId(taskDto.getTaskId());
        nursingTask.setEstimatedServerTime(taskDto.getEstimatedServerTime());
        nursingTask.setUpdateTime(new Date());
        return updateNursingTask(nursingTask);
    }
}
